package com.gmics.unifiq.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.gmics.android.R;
import com.gmics.unifiq.MainActivity;
import com.gmics.unifiq.ViewEvent;
import com.gmics.unifiq.ViewOpenEvent;
import com.gmics.unifiq.adapter.EventAdapter;
import com.gmics.unifiq.adapter.OpenEventAdapter;
import com.gmics.unifiq.controller.EntityController;
import com.gmics.unifiq.controller.UserFunctions;
import com.gmics.unifiq.entity.Event;
import com.gmics.unifiq.entity.Group;
import com.gmics.unifiq.entity.OpenEvent;
import com.gmics.unifiq.entity.User;

public class OpenEventFragment extends Fragment {
	private EntityController controller = new EntityController();
	private ListView oeLV;
	private String[] tabTitle;
	private int tabPos;
	private ArrayList<OpenEvent> oeArr;
	private ProgressDialog pDialog = null;
	private boolean dialogValid = false;
	private int index;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.open_event_layout, container,
				false);
		
	    if (android.os.Build.VERSION.SDK_INT > 9) {
	        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	        StrictMode.setThreadPolicy(policy);
	      }
	    
		new LoadEvents().execute();
		
		return rootView;
	}
	
    class LoadEvents extends AsyncTask<String, String, String> {
   	 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    		tabPos = getArguments().getInt("tabPos");
    		tabTitle = getResources().getStringArray(R.array.event_tab_title);
    		
		    index = ((MainActivity) getActivity()).getCurrentFragment();
		    if (index == 3){
				pDialog = new ProgressDialog(getActivity());
				pDialog.setMessage("Loading " + tabTitle[tabPos] + " university events...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(false);
				pDialog.show();
				dialogValid = true;
		    }
        }
 

        protected String doInBackground(String... args) {
    		UserFunctions uf = new UserFunctions();
    		HashMap<String, String> user = uf.getUser(getActivity());
			User tempUser = controller.retrieveUser(user.get("uid"));
			
    		int userID = tempUser.getId();
        	ArrayList<ArrayList<Integer>> idArr = controller.retrieveOpenEventAttendance(0, userID);
        	oeArr = controller.retrieveOpenEventByID(idArr.get(0));

    		Date currentDate = EntityController.dateTimeToDate(Calendar.getInstance().getTime());
    		
    		if (tabPos == 0){
    			for (int a = 0; a < oeArr.size(); a++){
    				Date eventDate = EntityController.dateTimeToDate(oeArr.get(a).getDateTime());
    				if (eventDate.compareTo(currentDate) <= 0){
    					oeArr.remove(a);
    					a--;
    				}
    			}
    		}
    		else if (tabPos == 1){
    			for (int a = 0; a < oeArr.size(); a++){
    				Date eventDate = EntityController.dateTimeToDate(oeArr.get(a).getDateTime());
    				if (eventDate.compareTo(currentDate) != 0){
    					oeArr.remove(a);
    					a--;
    				}
    			}
    		}
    		else if (tabPos == 2){
    			for (int a = 0; a < oeArr.size(); a++){
    				Date eventDate = EntityController.dateTimeToDate(oeArr.get(a).getDateTime());
    				if (eventDate.compareTo(currentDate) >= 0){
    					oeArr.remove(a);
    					a--;
    				}
    			}
    		}
            return null;
        }
 
        protected void onPostExecute(String file_url) {
			if (dialogValid){
				pDialog.dismiss();
			}
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
            		oeLV = (ListView) getActivity().findViewById(R.id.open_event_lv);
           
            		if (oeArr.size() != 0){
            			final OpenEventAdapter oeAdapter = new OpenEventAdapter(getActivity(), oeArr);
            			oeLV.setAdapter(oeAdapter);
            			
            			oeLV.setOnItemClickListener(new OnItemClickListener(){
            	
            				@Override
            				public void onItemClick(AdapterView<?> parent, View v, int position,
            						long id) {
            					// TODO Auto-generated method stub
            					Bundle b = new Bundle();
            					Intent viewOpenEventScreen = new Intent(getActivity(), ViewOpenEvent.class);
            					OpenEvent oe = (OpenEvent) oeAdapter.getItem(position);
            					b.putInt("tabPos", tabPos);
            					b.putSerializable("selectedOpenEvent", oe);
            					viewOpenEventScreen.putExtras(b);
            					startActivity(viewOpenEventScreen);
            				}	
            			}); 
            			
            		} else{
            			if (index == 3){
	            			String msg = "";
	
            				if (tabPos == 0){
            					msg += "You have not signed up for any university events. Sign up now!";
	            			}
	            			else{
	            				msg = "You do not have any " + tabTitle[tabPos] + " university events.";
	            			}
	            			
	            			ArrayAdapter<CharSequence> tempAdapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_list_item_1, new String[] {msg});
	            			oeLV.setAdapter(tempAdapter);
            			}
            		}
                }
            });
            
        }
    }
}
